package com.yht.weblog.jwt.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yht.weblog.common.utils.Response;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: yht
 * @date: 2023/12/7 17:38
 * @description:
 **/
public class ResultUtil {


    /**
     * 将结果以JSON格式写入HTTP响应
     * @param response 响应对象
     * @param result 响应结果
     * @throws IOException 如果写入响应过程中发生I/O错误
     */
    public static void ok(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8"); // 设置响应字符编码为UTF-8
        response.setStatus(HttpStatus.OK.value()); // 设置响应状态码为HttpStatus.OK
        response.setContentType("application/json"); // 设置响应内容类型为json
        PrintWriter writer = response.getWriter(); // 获取响应输出流

        ObjectMapper mapper = new ObjectMapper(); // 创建ObjectMapper对象
        writer.write(mapper.writeValueAsString(result)); // 将结果转换为json字符串并写入响应
        writer.flush(); // 刷新响应输出流
        writer.close(); // 关闭响应输出流
    }


    /**
     * 失败处理方法
     * @param response 响应对象
     * @param result 失败结果对象
     * @throws IOException IO异常
     */
    public static void fail(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8"); // 设置响应字符编码为UTF-8
        response.setStatus(HttpStatus.OK.value()); // 设置响应状态码为HttpStatus.OK
        response.setContentType("application/json"); // 设置响应内容类型为"application/json"
        PrintWriter writer = response.getWriter(); // 获取响应输出流

        ObjectMapper mapper = new ObjectMapper(); // 创建ObjectMapper对象
        writer.write(mapper.writeValueAsString(result)); // 将结果对象转换为JSON字符串并写入响应流
        writer.flush(); // 刷新响应流
        writer.close(); // 关闭响应流
    }


    /**
     * 失败响应
     * @param response 响应对象
     * @param status 状态码
     * @param result 响应数据对象
     * @throws IOException IO异常
     */
    public static void fail(HttpServletResponse response, int status, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8"); // 设置响应字符编码为UTF-8
        response.setStatus(status); // 设置响应状态码
        response.setContentType("application/json"); // 设置响应内容类型为json
        PrintWriter writer = response.getWriter(); // 获取响应输出流

        ObjectMapper mapper = new ObjectMapper(); // 创建ObjectMapper对象
        writer.write(mapper.writeValueAsString(result)); // 将Response对象转换为json字符串并写入响应流
        writer.flush(); // 刷新响应流
        writer.close(); // 关闭响应流
    }





}
